#
# @lc app=leetcode.cn id=124 lang=python3
#
# [124] 二叉树中的最大路径和
#

# @lc code=start
# Definition for a binary tree node.
import sys


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        ans = (-sys.maxsize - 1)

        def oneSideMax(root: TreeNode):
            nonlocal ans
            if not root:
                return 0
            left = max(0, oneSideMax(root.left))
            right = max(0, oneSideMax(root.right))

            # 后序遍历
            ans = max(ans, left + right + root.val)
            return max(left, right) + root.val

        oneSideMax(root)

        return ans

# @lc code=end
